package com.budwk.app.miniapp.utils;

import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class WechatMiniProgramTemplateMessageUtil {

    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    private static final String TEMPLATE_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN";
    private static final String APPID = "wx03d69fde959604e1";
    private static final String APPSECRET = "31d770915c6550b8db12c7a4448ef562";


    /**
     * 发送小程序模板消息
     *
     * @param openId 用户的 openid
//     * @param formId 表单id，通过form组件接口生成的id
//     * @param templateId 模板id，开发者提供的模板id
//     * @param page 跳转路径，所需跳转到的小程序页面路径
   //  * @param data 详细内容
     * @return 微信服务器返回的消息
     */
    public static String sendTemplateMessage2(String openId,String message,String eventId) throws Exception {

        String templateId="bquiIoDA7USZMMPuJHQSVk5OO9RCVNVNFwxC-rZWuzw";
        String page="/pages/index/detail?isOuter=true&id="+eventId;

        String formId="";
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("touser", openId);
        requestBody.put("template_id", templateId);
        requestBody.put("page", page);
        requestBody.put("form_id", formId);
        requestBody.put("data", message);

        String accessToken = getAccessToken();
        String url = TEMPLATE_MESSAGE_URL.replace("ACCESS_TOKEN", accessToken);
        ObjectMapper objectMapper = new ObjectMapper();
        String requestBodyString = objectMapper.writeValueAsString(requestBody);
        String result = HttpUtil.post(url, requestBodyString);
        return result;
    }

    /**
     * 获取 AccessToken
     *
     * @return AccessToken 字符串
     */
    private static String getAccessToken() throws Exception {
        String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
        String response = HttpUtil.get(url);

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(response);

        if (jsonNode == null || jsonNode.get("access_token") == null) {
            throw new Exception("获取 AccessToken 失败，错误信息：" + jsonNode.get("errmsg"));
        }

        return jsonNode.get("access_token").asText();
    }


    /***
     *
     * @param openId id
     * @param eventId 事件id
     * @param times 时间
     * @param address 地址
     * @return
     * @throws Exception
     */
    public static String sendTemplateMessage(String openId,String eventId,String times,String address)
        throws Exception {

        String templateId="bquiIoDA7USZMMPuJHQSVk5OO9RCVNVNFwxC-rZWuzw";
        String page="/pages/index/detail?isOuter=true&id="+eventId;

        // 微信小程序的 AppID 和 AppSecret
        String appid =APPID;
        String secret = APPSECRET;
        // 获取 access_token 的 API 地址
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token" + "?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        // 模板消息推送 API 地址
        String templateMessageUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";

        // 获取 access_token
        URL url = new URL(accessTokenUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.connect();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        String accessToken = response.toString().split(":")[1].split("\"")[1];


        String result = "";
        PrintWriter pw = null;
        BufferedReader br = null;

        // String thing3="您有一条新求助！如需接收其他求助点击授权";
        String thing3 = "如需接受网友求助，请进入再次授权";
        String thing2=address + "的网友需要您的帮助";
        String time1=times;
        // 构造模板消息发送请求
        String data = "{"
            + "\"touser\":\""+openId+"\","
            + "\"template_id\":\""+templateId+"\","
            + "\"page\":\""+page+"\","
            + "\"lang\":\""+"zh_CN"+"\","
           // + "\"miniprogram_state\":\""+"trial"+"\"," //上线，小程序正式版注释
            + "\"data\":{"
            + "\"thing3\":{\"value\":\""+thing3+"\"},"
            + "\"thing2\":{\"value\":\""+thing2+"\"},"
            + "\"time1\":{\"value\":\""+time1+"\"}"
            + "}"
            + "}";
        url = new URL(templateMessageUrl + accessToken);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        conn.setDoOutput(true);

        //新增
        // 获取URLConnection对象对应的输出流
//        OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
//        pw = new PrintWriter(outWriter);
//        // 发送请求参数
//        pw.print(data.getBytes());
//        // flush输出流的缓冲
//        pw.flush();
//        // 建立实际的连接
//        conn.connect();
//        br = new BufferedReader(new InputStreamReader(
//            conn.getInputStream()));
//        String line;
//        while ((line = br.readLine()) != null) {
//            result += line;
//        }

//        //旧版
        OutputStream os = conn.getOutputStream();
        os.write(data.getBytes());
        os.flush();
        os.close();

        // 获取模板消息发送结果
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
        response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        System.out.println(response.toString());

        return response.toString();
    }

}
